#include "adc_read.h"
#include <cstring>
#define LENGTH(array) (sizeof(array) / sizeof(array[0]))
extern rt_uint32_t personal_clock_tick;
extern char call_recording;
//  real_time_adc_data[2048] 用来实时记录adc数据
double real_time_adc_data[250] = {0};

// //  recording_adc_data[2048] 用来记录录音的adc数据
double recording_adc_data[250] = {0};
// 定义个用于存储ADC采样结果的缓冲区
unsigned short adc_buffer[3];
double adc_voltage[3];
/* 定义线程控制块 */
static struct rt_thread adc_read;

/* 定义线程控栈时要求RT_ALIGN_SIZE个字节对齐 */
ALIGN(RT_ALIGN_SIZE)
/* 定义线程栈 */
static rt_uint8_t rt_adc_read_stack[2048];
void adc_read_init(void *parameter) {
  //校准ADC
  HAL_ADCEx_Calibration_Start(&hadc);

  // int count = 0;
  while (1) {
    // 启动ADC的DMA传输，将采样结果存入adc_buffer�?
    HAL_ADC_Start_DMA(&hadc, (unsigned int *)adc_buffer,
                      sizeof(adc_buffer) / sizeof(adc_buffer[0]));
    for (char i = 0; i < 3; i++) {
      adc_voltage[i] = adc_buffer[i] * 3.3 / 4096.0;
    }
    if (personal_clock_tick < LENGTH(real_time_adc_data))
      real_time_adc_data[personal_clock_tick] = adc_voltage[1];
    if (call_recording == 1) {
      //当录音按键按下时,进行存储录音
      //关闭干扰,开始录音
      HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_1);
      if (personal_clock_tick < LENGTH(recording_adc_data))
        recording_adc_data[personal_clock_tick] = adc_voltage[1];
    }

    personal_clock_tick++;
    // rt_kprintf("[test]adc_voltage[0]=%f\r\n", adc_voltage[0]);
    // rt_kprintf("[test]adc_voltage[1]=%f\r\n", adc_voltage[1]);
    // rt_kprintf("[test]adc_voltage[2]=%f\r\n", adc_voltage[2]);
    // rt_thread_mdelay(2000);
    /* code */
  }
}
void adc_read_task(void) {
  rt_thread_init(&adc_read,                 /* 线程控制块 */
                 "adc_read",                /* 线程名字 */
                 adc_read_init,             /* 线程入口函数 */
                 RT_NULL,                   /* 线程入口函数参数 */
                 &rt_adc_read_stack[0],     /* 线程栈起始地址 */
                 sizeof(rt_adc_read_stack), /* 线程栈大小 */
                 3,                         /* 线程的优先级 */
                 100);                      /* 线程时间片 */
  rt_thread_startup(&adc_read);             /* 启动线程，开启调度 */
  rt_kprintf("adc_read running\r\n");
}